module WWW
  class Tkd
    class TbUser < ActiveRecord::Base
      #将旺旺传递的用户信息保存
      def self.save_from_aliww(domain_login_id,user_id,app_instance_id,hash_code,is_seller)
           if domain_login_id==nil || user_id==nil || app_instance_id==nil || hash_code==nil
              return nil
           end
           tb_user = TbUser::find_by_domain_login_id(domain_login_id)
           if tb_user==nil
                  tb_user = WWW::Tkd::TbUser.new
                  tb_user.user_id =user_id
                  tb_user.app_instance_id = app_instance_id
                  tb_user.is_seller=0
                  tb_user.domain_login_id=domain_login_id
                  tb_user.sip_sessionid=generate_random_string
                  tb_user.save
           else
               if tb_user.sip_sessionid==nil
                  tb_user.sip_sessionid=generate_random_string
                  tb_user.save
               end
           end
           #用户身份
           if tb_user.is_seller!=is_seller
              tb_user.is_seller=is_seller
              tb_user.save
           end
           tb_user
      end
      #将alisoft用户对象转换为Tkd对象
      def self.save_from_alisoft alisoft_user,is_seller
        tb_user = TbUser::find_by_user_id(alisoft_user.user_id)
        if tb_user==nil
          tb_user = WWW::Tkd::TbUser.new
          tb_user.user_id =alisoft_user.user_id
          tb_user.app_instance_id = alisoft_user.app_instance_id
          tb_user.is_seller=is_seller
          tb_user.save
        end
        tb_user.domain_login_id=alisoft_user.get_domain_login_id
        tb_user.save
        return tb_user
      end
      #更新用户的淘宝账号
      def self.update_domain_login_id id,domain_login_id
          user = self.find id
          if user!=nil && domain_login_id!=nil
             user.domain_login_id=domain_login_id
             user.save
          end
      end
      #更新sip_session
      def self.refresh_sip_sessionid id
            tb_user = TbUser::find_by_id(id)
            tb_user.sip_sessionid=generate_random_string
            tb_user.save
            tb_user.sip_sessionid
      end
      #获得随机字符串
      def self.generate_random_string(length=10)
          string = ""
          chars = ("A".."Z").to_a
          length.times do
            string << chars[rand(chars.length-1)]
          end
          string
       end

    end
  end
end
